const router = require('express').Router();
const fs = require('fs');
const db = require("./public/db");

//获取所有文章
router.get('/Article', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    db.sql('select * from Article', (err, data) => {
        if (err) res.send({ code: 400, msg: '数据库连接失败' });
        db.sql('select * from ArticleTag', (err, TagData) => {
            if (err) res.send({ code: 400, msg: '数据库连接失败' });
            res.send(JSON.stringify({ data: data.recordsets, TagData: TagData.recordsets }));
        });
    });
});

//添加文章
router.post('/add', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    let form = JSON.parse(req.query.form);
    //存入除tag以及content的其他内容
    db.sql(`
    insert into Article(Title,Cover,Summary,CreateAt,ViewCount,LikeCount,CategoryId)
    values(
        '${form.Title}',
        '${form.coverUrl}',
        '${form.Summary}',
        GETDATE(),
        0,
        0,
        '${form.Category}'
    )
    `, (err, data) => {
        if (err) res.send({ code: 400, msg: '数据库连接失败' })
        //获取最新存入的文章id
        db.sql(`select top 1 Id from Article order by id desc`, (err, data) => {
            if (err) res.send({ code: 400, msg: '数据库连接失败' });
            let ArticleId = data.recordset[0].Id;
            //存入tag
            db.sql(`
            insert into ArticleTag(ArticleId,TagId)
            values(
                ${ArticleId},
                '${form.Label}'
            )
             `, (err, TagData) => {
                if (err) res.send({ code: 400, msg: '数据库连接失败' });
            });
            //存入content
            db.sql(`
            insert into Comment(Content,CreateAt,ArticleId)
            values(
                '${form.Content}',
                GETDATE(),
                ${ArticleId}
            )
            `, (err, ContentData) => {
                if (err) res.send({ code: 400, msg: '数据库连接失败' });
            });
        });
    });



    res.send('hello');
});

//上传封面
router.all('/upload', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    if (req.file) {
        let filename = req.file.originalname;
        let oldPath = "./public/tmp/" + req.file.filename;
        let newPath = "./public/tmp/" + filename;
        fs.rename(oldPath, newPath, (err) => {
            if (err) {
                console.log(err);
                return
            }
        });
        let path = "http://" + req.headers.host + "/tmp/" + filename;
        res.send(path);
    } else {
        res.send("预检返回");
    }
})

//更新封面
router.all('/updateImg', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    if (req.file) {
        let filename = req.file.originalname;
        let oldPath = "./public/tmp/" + req.file.filename;
        let newPath = "./public/tmp/" + filename;
        fs.rename(oldPath, newPath, (err) => {
            if (err) {
                console.log(err);
                return
            }
        });
        let path = "http://" + req.headers.host + "/tmp/" + filename;
        res.send(path);
    } else {
        res.send("预检返回");
    }
})

//更新文章数据
router.post('/update', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    let form = JSON.parse(req.query.data)
    //console.log('form',form)
    db.sql(`
    update Article set
    Title = '${form.Title}',
    Cover = '${form.Cover}',
    Summary = '${form.Summary}',
    ViewCount = '${form.ViewCount}',
    LikeCount = '${form.LikeCount}',
    CategoryId= '${form.CategoryId}'
    where Id = '${form.Id}'
    `, (err, data) => {
        if (err) res.send({ code: 400, msg: '数据库连接失败' });
        if (data.rowsAffected.length > 0) {
            db.sql(`
            update ArticleTag set TagId = '${form.TagName}'
            where ArticleId = '${form.Id}'
            `, (err, data) => {
                if (err) res.send({ code: 400, msg: '数据库连接失败' });
                if (data.rowsAffected.length > 0) {
                    res.send('修改成功');
                }
            });
        }
    });
})

//删除文章
router.post('/del', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    db.sql(`delete from Article where Id = ${req.query.id}`, (err, data) => {
        if (err) res.send({ code: 400, msg: '数据库连接失败' });
        if (data.rowsAffected.length > 0) {
            db.sql(`delete from ArticleTag where ArticleId = ${req.query.id}`, (err, TData) => {
                if (err) res.send({ code: 400, msg: '数据库连接失败' });
                if (TData.rowsAffected.length > 0) {
                    db.sql(`delete from Comment where ArticleId = ${req.query.id}`, (err, Cdata) => {
                        if (err) res.send({ code: 400, msg: '数据库连接失败' });
                        if (TData.rowsAffected.length > 0) {
                            res.send('删除成功');
                        }
                    })
                }
            });
        }
    });
});

//获取文章数据
router.get('/Comment',(req,res)=>{
    res.setHeader('Access-Control-Allow-Origin', '*');
    db.sql('select * from Comment',(err,data)=>{
        res.send(data);
    });
});

module.exports = router;